<?php
set_include_path('..');
include_once('settings.php');
session_start();

$result["success"] = 0;
$result["message"] = MESSAGE_SUCCESS;

try {
    if (!isset($_SESSION["user"])){
        throw new Exception(MESSAGE_NOT_LOGGED_IN);
    }

    if((time() < START_TIME || time() > END_TIME) && $_SESSION["user"]["security_level"] < SECURITY_LEVEL_ADMIN){
        throw new Exception(MESSAGE_RESERVATION_CLOSED);
    }

    if (!isset($_POST["action"])){
        throw new Exception(MESSAGE_FAILED);
    }

    $action = $_POST["action"];

    $reservation = new InteractiveReservation();
    $administration = new OrderAdministration();

    switch($action){
        case("getReserved"):
            $data = $reservation->GetReservedSeats();
            $result["data"] = $data;
            $result["success"] = $data ? true : false;
            break;
        case("reserveSeat"):
            $id = $_POST["id"];
            $result["success"] = $reservation->TryReserveSeat($id);
            $result["data"] = $reservation->GetUserSeats();
            break;
        case("unreserveSeat"):
            $id = $_POST["id"];
            $result["success"] = $reservation->TryUnreserveSeat($id);
            $result["data"] = $reservation->GetUserSeats();
            break;
        case("reserveTable"):
            $id = $_POST["id"];
            $rse =  $reservation->TryReserveTable($id, true);
            if (!$rse){
                throw new Exception(MESSAGE_NO_FREE_TABLE);
            }
            $result["success"] = $rse;
            $result["data"] = $reservation->GetUserSeats();
            break;
        case("magic"):
            $result["success"] = $reservation->TryReserveTable();
            $result["data"] = $reservation->GetUserSeats();
            break;
        case("order"):
            $result["success"] = $reservation->Order();
            $result["data"] = $reservation->GetUserOrderedSeats();
            break;
        case("refresh"):
            $result["success"] = 1;
            $result["userSeats"] =        $reservation->GetUserSeats();
            $result["reservedSeats"] =    $reservation->GetReservedSeats();
            $result["orderedSeats"] = $reservation->GetUserOrderedSeats();
            $result["paidSeats"] = json_encode($administration->GetPaidSeat());
            break;
        default:
            throw new Exception(MESSAGE_FAILED);
            break;
    }

} catch (Exception $e){
    $result["success"] = 0;
    $result["message"] = $e->getMessage();
}

echo json_encode($result);